package com.pet.platform.service.impl;

import com.pet.platform.common.Constants;
import com.pet.platform.common.PageResult;
import com.pet.platform.dto.CommentDTO;
import com.pet.platform.dto.CommentQueryDTO;
import com.pet.platform.entity.Comment;
import com.pet.platform.entity.Post;
import com.pet.platform.entity.User;
import com.pet.platform.exception.BusinessException;
import com.pet.platform.mapper.CommentMapper;
import com.pet.platform.mapper.PostMapper;
import com.pet.platform.service.CommentService;
import com.pet.platform.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserService userService;

    @Override
    public Comment findById(Long id) {
        return commentMapper.findById(id);
    }

    @Override
    public PageResult<CommentDTO> findPage(CommentQueryDTO queryDTO) {
        Map<String, Object> params = new HashMap<>();
        params.put("postId", queryDTO.getPostId());
        params.put("userId", queryDTO.getUserId());
        params.put("parentId", queryDTO.getParentId());
        params.put("status", queryDTO.getStatus());
        params.put("offset", queryDTO.getOffset());
        params.put("pageSize", queryDTO.getPageSize());
        params.put("orderBy", queryDTO.getOrderBy());
        params.put("isAsc", queryDTO.getIsAsc());

        List<Comment> comments = commentMapper.findList(params);
        Long total = commentMapper.count(params);

        List<CommentDTO> commentDTOs = comments.stream().map(this::convertToDTO).collect(Collectors.toList());

        return new PageResult<>(commentDTOs, total, queryDTO.getPageNum(), queryDTO.getPageSize());
    }

    @Override
    public List<CommentDTO> findByPostId(Long postId) {
        List<Comment> comments = commentMapper.findByPostId(postId);
        return comments.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void create(CommentDTO commentDTO) {
        Post post = postMapper.findById(commentDTO.getPostId());
        if (post == null) {
            throw new BusinessException("帖子不存在");
        }

        User currentUser = userService.getCurrentUser();
        
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDTO, comment);
        comment.setUserId(currentUser.getId());
        comment.setStatus(Constants.STATUS_NORMAL);
        
        commentMapper.insert(comment);
        postMapper.updateComments(commentDTO.getPostId(), true);
    }

    @Override
    @Transactional
    public void update(Long id, CommentDTO commentDTO) {
        Comment comment = findById(id);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }

        User currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(comment.getUserId()) && !Constants.ROLE_ADMIN.equals(currentUser.getRole())) {
            throw new BusinessException("没有权限修改此评论");
        }

        comment.setContent(commentDTO.getContent());
        commentMapper.update(comment);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Comment comment = findById(id);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }

        User currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(comment.getUserId()) && !Constants.ROLE_ADMIN.equals(currentUser.getRole())) {
            throw new BusinessException("没有权限删除此评论");
        }

        commentMapper.delete(id);
        postMapper.updateComments(comment.getPostId(), false);
    }

    private CommentDTO convertToDTO(Comment comment) {
        CommentDTO dto = new CommentDTO();
        BeanUtils.copyProperties(comment, dto);
        
        // 安全地获取用户名
        User user = comment.getUser();
        if (user != null) {
            dto.setUsername(user.getUsername());
            dto.setUserAvatar(user.getAvatar());
        }
        
        // 安全地获取父评论信息
        if (comment.getParentId() != null) {
            Comment parentComment = findById(comment.getParentId());
            if (parentComment != null && parentComment.getUser() != null) {
                dto.setParentUsername(parentComment.getUser().getUsername());
            }
        }
        
        return dto;
    }
} 